package cn.com.infcn.util;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Date;
import java.util.concurrent.*;

/**
 * Created by cc on 2016/12/27.
 *
 * @author jijs
 */
public class HttpUtils {




    /**
     * 向指定URL发送GET方法的请求
     *
     * @param url 发送请求的URL
     */
    public static void sendGet(String url, HttpServletResponse response) {
        String filePath = FileUtils.getFilePath();
        ExecutorService executorService = Executors.newSingleThreadExecutor();
        OutputStream os = null;
        InputStream is = null;
        try {
            Future<Boolean> future = executorService.submit(new HttpCallableTask(url, filePath));
            boolean result = future.get(ConfigUtils.getHttpTimeOut(), TimeUnit.SECONDS);
            if (result) {
                os = response.getOutputStream();

                is = new BufferedInputStream(new FileInputStream(filePath), 1024);
                byte[] b = new byte[1024];
                int read;
                while ((read = is.read(b, 0, 1024)) > 0) {
                    os.write(b, 0, read);
                }
                os.flush();
            }
        } catch (Exception e) {
            response.setStatus(404);
            response.setCharacterEncoding("utf-8");
            response.setContentType("text/html");
            try (PrintWriter writer = response.getWriter()) {
                writer.write("<h2>File not found</h2><hr>" + new Date());
                writer.flush();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }

    }



    public static void main(String[] args) {


    }


}


